import React, { useContext } from 'react'
import { useLocalStore } from 'mobx-react'
import createStore from './createStore'

// 根据createStore的返回值自动定义Store的类型
export type Store = ReturnType<typeof createStore>

// 创建上下文组件对象storeContext
const storeContext = React.createContext<Store | null>(null)

// 定义组件StoreProvide 接收storeContext 对象带有的值
export const StoreProvide = ({ children }: { children: any }) => {
  const store = useLocalStore(createStore)
  return (
    // 封装storeContext组件自生成的Provide组件
    <storeContext.Provider value={store}>{children}</storeContext.Provider>
  )
}

// 自定义hook来使用store
const useStores = () => {
  // 获取storeContext对象带来的value
  const store = useContext(storeContext)

  // 如果获取不到store则应该是未在Provider组件下
  if (!store) {
    throw new Error('useStore must be used whitin a StoreProvide! ')
  }
  return store
}

export default useStores
